import axios from "axios"
import router from "@/router"
import { useUserStore } from "@/stores/userStore"
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'

// 创建 axios 实例
const request = axios.create({
    baseURL: 'http://127.0.0.1:8081/',
    timeout: 5000,
})

request.defaults.withCredentials = true

// axios 请求拦截器
request.interceptors.request.use(config => {
    // 从pinia中获取用户token
    const userStore = useUserStore()
    const token = userStore.token
    // 若token存在，则将token放入请求头中
    if (token) {
        config.headers.Authorization = token
    }
    return config
}, e => Promise.reject(e))

// axios 响应拦截器
request.interceptors.response.use(response => {
    // 提示错误消息
    const { data: res } = response
    // token失效处理
    if (res.code === 4001) {
        const userStore = useUserStore()
        userStore.clearUserInfo()
        ElMessage({
            type: 'warning',
            message: '登录已过期，请重新登录'
        })
        router.push('/login')
    } else if (res.code != 2000) {
        ElMessage({
            type: 'error',
            message: res.msg
        })
    }
    return response.data
}, e => {
    // 统一的错误提示
    ElMessage({
        type: 'warning',
        message: '服务器繁忙'
    })
    return Promise.reject(e)
})

export default request